
var pageBean = null;
var dataList = {};
var clientLevles = {};

$(document).ready(function(e) {
	 $(".select1").uedSelect({
			width : 345			  
	});
	$(".select2").uedSelect({
		width : 167  
	});
	$(".select3").uedSelect({
		width : 100
	});		

	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	$("#add").click(add);

	search(1);	 
	initialClientLevle();
});


function getRequestJson(requestJson){	
	if(requestJson == null){
		requestJson = {};
	}	
	
	var addclientLevle = $("#addclientLevle").val();
	var clientLevel = clientLevles[addclientLevle];
	requestJson['clientLevel'] = clientLevel;
	var clientClassificationName = $("INPUT[name='clientClassificationName']").val();
	var addclientLevle = $("select[name='clientLevle']").val();
	if(addclientLevle == '-1'){
		alert("请选择客户等级");
		return;
	}
	if(clientClassificationName == ''){
		alert("请输入客户分类！")
		return;
	}
	requestJson['clientClassificationName'] = clientClassificationName;
	var displaySequence = $("INPUT[name='displaySequence']").val();
	if(displaySequence == ''){
		displaySequence = '999999';
	}	
	requestJson['displaySequence'] = displaySequence;
	return requestJson;
}



function save(){
	
	var requestJson = {};
	requestJson = getRequestJson(requestJson);
	if(requestJson == false){
		return false;
	}
	$.ajax({
        url: '/euc/clientclassification/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataAdd']").hide();
            	search(pageBean.currentPage);
        	}
        	alert(datas.message);        	
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function update(data){
	if(data == null){
		return false;
	}
	data = getRequestJson(data);
	if(data == false){
		return false;
	}
	
	
	$.ajax({
        url: '/euc/clientclassification/update',
        data:JSON.stringify(data),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//var result = JSON.stringify(datas);
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataAdd']").hide();
            	search(pageBean.currentPage);
        	}
        	alert(datas.message);    
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataAdd']").hide();
}

function clearFrom(){
	//$("#addclientLevle").children('option').eql(0).trigger('change');
	$("INPUT[name='clientClassificationName']").val('');
	$("INPUT[name='displaySequence']").val('');
	// $("select[name='clientLevle']").val('-1');
    $("#addclientLevle").val("-1").trigger("change");
}

function setFrom(data){
	$("#addclientLevle").val(data.clientLevel.id).trigger('change');
	$("INPUT[name='clientClassificationName']").val(data.clientClassificationName);
	$("INPUT[name='displaySequence']").val(data.displaySequence);
}

function add(){
	$("#operator").html("添加");
	clearFrom();
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataAdd']").show();
}


function detail(id){
	var currentData = dataList[id];
	clearFrom();
	setFrom(currentData);
	$("#operator").html("编辑");
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataAdd']").show();	
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		update(currentData);
	});
}

function deleteData(id){
	 if(confirm("确定删除该记录?")){
		var requestJson = {id:id};
		$.ajax({
	        url: '/euc/clientclassification/delete',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	//alert(JSON.stringify(result));
				if(result.status == 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					search(cur);
	        	}else{
	        		alert(result.message);  
	        	}	        	
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}


function search(currentPage){
	
	var parameter = $("INPUT[name='parameter']").val();

	var requestJson = {currentPage:currentPage,data:{like:{'clientClassificationName':parameter},equals:{'clientClassificationName':''}}};
		
	$.ajax({
        url: '/euc/clientclassification/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
        		if(data.clientLevel != null) {
                    var html = '<tr>';
                    html += '<td style="width:70px;">' + (i + 1) + '</td>';
                    if (data.clientLevel.clientLevelName == null || data.clientLevel.clientLevelName == undefined) {
                        data.clientLevel.clientLevelName = '';
                    }
                    html += '<td style="width:160px;">' + (data.clientLevel.clientLevelName) + '</td>';
                    html += '<td style="width:160px;">' + data.clientClassificationName + '</td>';
                    html += '<td style="width:160px;">' + data.createTime + '</td>';
                    //html += '<td style="width:160px;">' + data.displaySequence + '</td>';
                    html += '<td style="width:170px;"><a href="javascript:detail(' + data.id + ');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteData(' + data.id + ');" class="tablelink">删除</a></td>';
                    html += '</tr>';
                    $("#userTable").append(html);
                    dataList[data.id] = data;
                }
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');
        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function initailPageNumber(totalPage,currentPage,pageLength){				
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

function initialClientLevle(){
	$.ajax({
        url: '/euc/clientlevel/list',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	var clientLevle = $("SELECT[name='clientLevle']");
        	$.each(result,function(index,data){
           		$('<option value="'+ data.id +'">'+ data.clientLevelName +'</option>').appendTo($(clientLevle));
           		clientLevles[data.id] = data;
   			});
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

